package com.genshang.restaurant.util;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Service
public class QiNiuOSSUtil {
    private Logger logger = LoggerFactory.getLogger(QiNiuOSSUtil.class);
    private static final String accessKey = "jBZkLLSRsi7N-uLQCBusls_lJW7YQIGHACXsFKyW";
    private static final String secretKey = "fZ_oAQhRs23csC9SyyUjaZIxAm6K_ARbUe-23Yi0";
    private static final String bucket = "genshang-sh";
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};
    private static String BASE_URL = "http://picture.genshang-sh.cn/";
    static Auth auth = Auth.create(accessKey, secretKey);

    // 创建上传对象
    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.region0());
    UploadManager uploadManager = new UploadManager(cfg);

    private boolean checkImageType(String originalFilename) {
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(originalFilename, type)) {
                isLegal = true;
                break;
            }
        }
        return isLegal;
    }

    public Map<String, Object> uploadPicture(MultipartFile uploadFile) {
        Map<String, Object> resultMap = new HashMap<>();
        logger.info("上传进入");
        boolean checkType = checkImageType(uploadFile.getOriginalFilename());
        if (!checkType) {
            resultMap.put("success", "0");
            resultMap.put("message", "图片格式不对");
            return resultMap;
        }
        try {
            // 文件新路径
            String fileName = getNewFileName(uploadFile.getOriginalFilename());
            String upToken = auth.uploadToken(bucket);
            byte[] bytes = uploadFile.getBytes();
            Response res = uploadManager.put(bytes, fileName, upToken);
            // 打印返回的信息
            logger.info(res.bodyString());
            logger.info("=============================================");
            logger.info("");
            resultMap.put("success", "1");
            resultMap.put("message", BASE_URL + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("success", "0");
            resultMap.put("message", "内部报错");
            return resultMap;
        }
        return resultMap;
    }

    private String getNewFileName(String sourceFileName) {
        String fileName =
                System.currentTimeMillis() + RandomUtils.nextInt() + "."
                        + StringUtils.substringAfterLast(sourceFileName, ".");
        return fileName;
    }

}
